import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
const Reg = () => import('@/views/Reg/reg.vue')
const Login = () => import('@/views/Login/Login.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Home/Home.vue')
const ArticleList = () => import('@/views/Article/ArticleList.vue')
const ArticleSort = () => import('@/views/Article/ArticleSort.vue')
const Avatar = () => import('@/views/User/Avatar.vue')
const Base = () => import('@/views/User/Base.vue')
const Password = () => import('@/views/User/Password.vue')

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'art-cate', component: ArticleSort },
      { path: 'art-list', component: ArticleList },
      { path: 'user-info', component: Base },
      { path: 'user-avatar', component: Avatar },
      { path: 'user-pwd', component: Password }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局守卫
router.beforeEach((to, form, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    // 不需要权限，直接放行
    next()
  } else {
    // 需要判断是否登录
    if (store.state.token) {
      // 有值，放行
      next()
    } else {
      // 没有 token，强制跳转到登录页面
      next('/login')
    }
  }
})

export default router
